package fr.jade.fraclite.control.lifecycle;

import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.NoSuchInterfaceException;
import org.objectweb.fractal.api.control.ContentController;
import org.objectweb.fractal.api.control.IllegalLifeCycleException;
import org.objectweb.fractal.api.control.LifeCycleController;
import org.objectweb.fractal.api.factory.InstantiationException;
import org.objectweb.fractal.util.Fractal;

import fr.jade.fraclite.InitializationContext;
import fr.jade.fraclite.api.Controller;

public class BasicLifeCycleController implements Controller,
		LifeCycleController {

	protected String state = LifeCycleController.STOPPED;
	protected ContentController cc = null;
	protected LifeCycleController innerImpl = null;

	public void initFcController(final InitializationContext ic)
			throws InstantiationException {
		if (ic.content instanceof LifeCycleController) {
			innerImpl = (LifeCycleController) ic.content;
		}
		try {
			cc = (ContentController) ic.getInterface("content-controller");
		} catch (InstantiationException ignored) {
		}
		state = LifeCycleController.STOPPED;
	}

	public String getFcState() {
		if (innerImpl == null) {
			return state;
		} else {
			return innerImpl.getFcState();
		}
	}

	public void startFc() throws IllegalLifeCycleException {
		if (cc != null) {
			for (Component sub : cc.getFcSubComponents()) {
				try {
					LifeCycleController lcc = Fractal
							.getLifeCycleController(sub);
					lcc.startFc();
				} catch (NoSuchInterfaceException ignored) {
				}
			}
		}
		if (innerImpl == null) {
			state = LifeCycleController.STARTED;
		} else {
			innerImpl.startFc();
		}
	}

	public void stopFc() throws IllegalLifeCycleException {
		if (cc != null) {
			for (Component sub : cc.getFcSubComponents()) {
				try {
					LifeCycleController lcc = Fractal
							.getLifeCycleController(sub);
					lcc.stopFc();
				} catch (NoSuchInterfaceException ignored) {
				}
			}
		}
		if (innerImpl == null) {
			state = LifeCycleController.STOPPED;
		} else {
			innerImpl.stopFc();
		}
	}

}
